package com.list88zhu.android.sunflower.jetpack.paging;

import android.arch.paging.PagedListAdapter;
import android.support.annotation.NonNull;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.list88zhu.android.sunflower.R;
import com.list88zhu.android.sunflower.jetpack.room.Plant;
import com.list88zhu.android.sunflower.utils.DateTimeUtils;

/**
 * <pre><code>
 *
 *  </code></pre>
 *
 * @author zhuyingming@qmtv.com
 * @date 2018/8/26
 */
public class PlantAdapter extends PagedListAdapter<Plant, PlantAdapter.PlantViewHolder> {


    public PlantAdapter() {
        super(DIFF_CALLBACK);
    }


    @NonNull
    @Override
    public PlantViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_plant_query_item, viewGroup, false);
        return new PlantViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PlantViewHolder plantViewHolder, int i) {
        Plant plant = getItem(i);
        if(plant != null) {
            plantViewHolder.bindTo(plant);
        }
    }

    public final static DiffUtil.ItemCallback<Plant> DIFF_CALLBACK =
        new DiffUtil.ItemCallback<Plant>() {
            @Override
            public boolean areItemsTheSame(@NonNull Plant plant, @NonNull Plant t1) {
                return plant.getId() == t1.getId();
            }

            @Override
            public boolean areContentsTheSame(@NonNull Plant plant, @NonNull Plant t1) {
                return plant.equals(t1);
            }
        };

    class PlantViewHolder extends RecyclerView.ViewHolder {

        TextView titleView;
        TextView contentView;
        TextView beginView;
        TextView endView;
        TextView executorView;

        public PlantViewHolder(@NonNull View itemView) {
            super(itemView);
            titleView = itemView.findViewById(R.id.tv_title);
            contentView = itemView.findViewById(R.id.tv_content);
            beginView = itemView.findViewById(R.id.tv_begin);
            endView = itemView.findViewById(R.id.tv_end);
            executorView = itemView.findViewById(R.id.tv_executor);
        }

        public void bindTo(Plant plant) {
            titleView.setText(plant.getTitle());
            contentView.setText(plant.getContent());
            beginView.setText(DateTimeUtils.date2String(plant.getBeginDate()));
            endView.setText(DateTimeUtils.date2String(plant.getEndDate()));
            executorView.setText(plant.getExecutor());
        }
    }
}
